package cn.com.thinvent.dispatch.service.biz.impl;

import cn.com.thinvent.dispatch.dao.*;
import cn.com.thinvent.dispatch.entity.*;
import cn.com.thinvent.dispatch.entity.response.ChatResponse;
import cn.com.thinvent.dispatch.entity.response.ModelTaskResponse;
import cn.com.thinvent.dispatch.entity.response.PagedGridResult;
import cn.com.thinvent.dispatch.entity.response.ResultDetailResponse;
import cn.com.thinvent.dispatch.service.biz.IndicatorConfigService;
import cn.com.thinvent.dispatch.service.biz.util.DataBaseUtil;
import cn.com.thinvent.dispatch.service.biz.util.DataConvertUtils;
import cn.com.thinvent.dispatch.service.biz.util.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.swagger2.mappers.ModelMapper;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Component
public class IndicatorConfigServiceImpl implements IndicatorConfigService {


    @Resource
    private IndicatorConfigMapper indicatorConfigMapper;
    @Resource
    private IndicatorMapper indicatorMapper;
    @Resource
    private  FileContentMapper fileContentMapper;
    @Resource
    private ModelResultMapper modelResultMapper;
    @Resource
    private  ModelDatasourceResultMappingMapper modelDatasourceResultMappingMapper;
    @Resource
    private ModelErrorMapper modelErrorMapper;
    @Resource
    private IndicatorResultMapper indicatorResultMapper;
    @Override
    public PagedGridResult<IndicatorConfig> list(Integer userId,String fileName, Integer pageNum, Integer pageSize) {
        PagedGridResult<IndicatorConfig> pagedGridResult = new PagedGridResult<>();
        Integer pageBegin = (pageNum - 1) * pageSize;
        List<IndicatorConfig> list = indicatorConfigMapper.queryAllByLimit(userId,fileName, pageBegin, pageSize);
        Long count = indicatorConfigMapper.count(userId,fileName);
        pagedGridResult.setRows(list);
        pagedGridResult.setRecords(count);
        pagedGridResult.setTotal((Integer.parseInt(count.toString()) + pageSize - 1 )/ pageSize);
        pagedGridResult.setPage(pageNum);
        return pagedGridResult;
    }
   // 修改指标集配置
   @Override
   public IndicatorConfig saveOrUpdate(IndicatorConfig indicatorConfig) {
       Date date = new Date();
       if(indicatorConfig.getId() == null) {
           indicatorConfig.setCreateTime(date);
           indicatorConfig.setUpdateTime(date);
           indicatorConfigMapper.insert(indicatorConfig);
           System.out.println(indicatorConfig.getIndicatorId());
       } else {
           indicatorConfig.setUpdateTime(date);
           indicatorConfigMapper.update(indicatorConfig);
       }
       return indicatorConfig;
   }
    @Override
    public Integer delete(Integer id) {
        // 删除任务
        return indicatorConfigMapper.deleteById(id);
    }
    @Override
    public void actionNow(Integer id, Integer userId) {
        // 查询任务信息

        IndicatorConfig indicatorConfig = indicatorConfigMapper.queryById(id);

        if(null != indicatorConfig) {
            // 指标id “1，2，3”
            String indicatorId = indicatorConfig.getIndicatorId();
            //  “1，2，3” = 》[1,2,3]
            String[] splitIds = indicatorId.split(",");
            List<Integer> ids = Arrays.stream(splitIds)
                    .map(String::trim) // 移除可能的空白字符
                    .map(Integer::parseInt) // 将字符串转换为整数
                    .collect(Collectors.toList());
            // 查询指标信息
            List<Indicator> indicators = indicatorMapper.getListByIds(ids);
            // 存放指标名字
            List<String> names = indicators.stream()
                    .map(Indicator::getName)
                    .collect(Collectors.toList());
            // 所有指标
            String indicatorString = String.join("、", names);
            // 执行条件
            String example = "根据以下文本，请仅提取出'"+indicatorString+"'中的信息。若某项信息提取不出，则该项设为null。 " +
                    "输出结果应遵守以下要求： " +
                    "若文本中未找到'"+indicatorString+"'某项的值，则该值设为null，一定不要编造数据。" +
                    "提取仅聚焦于'"+indicatorString+"'中的各项信息，并输出严格遵守带双引号的json格式，不要输出重复或多余的内容.\n";
                    /*"指令：请逐步思考，从以下的文本中提取出["+indicatorString+"]," +
                    "请不要输出多余的字，只需要输出json,不要重复json的值和内容,若某项提取不出则该项为null。\n";*/


            // 查询非结构化文档内容
            String fileContent = fileContentMapper.queryById(indicatorConfig.getSourceId()).getContent();
            String prompt = example + fileContent;
            String s = null;
            try {
                // 发送http请求到模型

                Map<String, String> map = new HashMap<>();
                map.put("prompt", prompt);
                s = JSONObject.toJSONString(map);
                String postString = HttpClientUtil.doPostForChat("http://60.204.204.87:80",s);
                // 解析返回的字符串
                ChatResponse chatResponse1 = JSON.parseObject(postString, ChatResponse.class);

                /*Map<String, Object> map1 = new HashMap<>();
                map1.put("prompt", example);
                map1.put("history", chatResponse1.getHistory());
                s = JSONObject.toJSONString(map1);
                String postString1 = HttpClientUtil.doPost("http://60.204.204.87:80",s);
                // 解析返回的字符串
                ChatResponse chatResponse = JSON.parseObject(postString1, ChatResponse.class);*/
                Pattern pattern = Pattern.compile("\\{([^}]*)\\}");
                Matcher matcher = pattern.matcher(chatResponse1.getResponse());
                System.out.println("原始: "+chatResponse1.getResponse());
                String contentInsideBraces = null;
                String newRes = null;
                if (matcher.find()) {
                    contentInsideBraces = matcher.group(1); // 使用 group(1) 来获取第一个分组
                    System.out.println("正则："+contentInsideBraces);
                } else {
                    newRes = "提取有误";
                    System.out.println("没有找到匹配项");
                }

                //指标匹配结果
               if(!Objects.equals(newRes, "提取有误")){
                   ObjectMapper objectMapper = new ObjectMapper();
                   JsonNode rootNode = objectMapper.readTree("{"+contentInsideBraces+"}"); // 解析JSON字符串

                   ObjectNode filteredNode = objectMapper.createObjectNode(); // 创建一个新的ObjectNode来存储筛选后的字段

                   for (String name : names) {
                       if (rootNode.has(name)) { // 如果字段存在，则设置对应的值
                           filteredNode.set(name, rootNode.get(name));
                       } else { // 如果字段不存在，则设置null值
                           filteredNode.putNull(name);
                       }
                   }

                   newRes = objectMapper.writeValueAsString(filteredNode); // 将新的ObjectNode转换为JSON字符串

               }

                // 保存结果到数据库
                IndicatorResult indicatorResult = new IndicatorResult();
                indicatorResult.setResult(newRes);
                indicatorResult.setIndicatorConfigId(id);
                indicatorResult.setUserId(userId);
                Date date = new Date();
                indicatorResult.setCreateTime(date);
                indicatorResult.setUpdateTime(date);
                indicatorResult.setSourceId(indicatorConfig.getSourceId());
                indicatorResult.setContent(fileContent);
                System.out.println("最终结果1："+newRes);
                System.out.println("最终结果2："+indicatorResult.getResult());
                System.out.println(indicatorResult.getIndicatorConfigId());
                indicatorResultMapper.insert(indicatorResult);


                // 保存任务和数据源和结果之间的映射
                ModelDatasourceResultMapping modelDatasourceResultMapping = new ModelDatasourceResultMapping();
                modelDatasourceResultMapping.setDatasourceId(indicatorConfig.getSourceId());
                modelDatasourceResultMapping.setResultId(indicatorResult.getId());
                modelDatasourceResultMapping.setDataKeyword(fileContent);
                modelDatasourceResultMapping.setTaskId(id);
                Date d = new Date();
                modelDatasourceResultMapping.setCreateTime(d);
                modelDatasourceResultMapping.setUpdateTime(d);
                modelDatasourceResultMappingMapper.insert(modelDatasourceResultMapping);
            } catch (Throwable throwable) {
                ModelError modelError = new ModelError();
                modelError.setTaskId(id);
                modelError.setDatasourceId(indicatorConfig.getSourceId());
                modelError.setRequestParam(s);
                modelError.setMessage(throwable.getMessage());
                Date date = new Date();
                modelError.setCreateTime(date);
                modelError.setUpdateTime(date);
                modelErrorMapper.insert(modelError);
            }
            // 修改任务执行状态
            indicatorConfig.setStatus("已执行");

            indicatorConfigMapper.update(indicatorConfig);
            System.out.println(indicatorConfig.getStatus());
        }
    }
    //重新执行
    @Override
    public void renewAction(Integer id, Integer userId) {

        // 删除结果信息
        indicatorResultMapper.deleteById(id,userId);
        actionNow(id,userId);
    }
   /* 查看结果*/
    @Override
    public IndicatorResult viewResult(Integer id, Integer userId){

        return indicatorResultMapper.queryById(id);
    }
    @Override
    public String aIChat(String prompt) {

        Map<String, String> map = new HashMap<>();
        map.put("prompt", prompt);
        System.out.println("----------------------" +prompt);
        String s = JSONObject.toJSONString(map);
        String tmp = HttpClientUtil.doPostForChat("http://60.204.204.87:8888",s);
//        String tmp = HttpClientUtil.doPost("http://localhost:8888",s);
        // 解析返回的字符串
        ChatResponse chatResponse = JSON.parseObject(tmp, ChatResponse.class);
        String res = "";
        res = chatResponse.getResponse();
        System.out.println(res);
        // 解析返回的字符串
        return res;
    }
    public String aIChatTest(String prompt) {
        // 找出 条件列表字符串

        Pattern pattern1 = Pattern.compile("\\[(.*?)\\]");  // 匹配和提取字符串中方括号内内容,这里即用于获取所需提取的指标
        Matcher matcher1 = pattern1.matcher(prompt);

        String[] fields = {};
        if (matcher1.find()) {
            String exampleList = matcher1.group(); // 获取整个匹配的内容，包括方括号
            String trimmedExampleList = exampleList.substring(1, exampleList.length() - 1);
            fields = trimmedExampleList.split(",");

        } else {
            System.out.println("没有找到匹配的方括号。");
        }

        Map<String, String> map = new HashMap<>();
        map.put("prompt", prompt);
        System.out.println("----------------------" +prompt);
        String s = JSONObject.toJSONString(map);
        String tmp = HttpClientUtil.doPostForChat("http://60.204.204.87:8888",s);

//        String tmp = HttpClientUtil.doPostForChat("http://localhost:8888",s);
        // 解析返回的字符串
        ChatResponse chatResponse = JSON.parseObject(tmp, ChatResponse.class);
        String res = "";
        res = chatResponse.getResponse();
        System.out.println("模型返回结果："+res);
        // 去掉首尾单引号
        String cleanedStr = res.replaceAll("^'|'$", "");
        //中间单引号变双引号
        String replacedStr = cleanedStr.replace("'", "\"");
        //清除 {}[] 可能出现不完整的情况
        String cleanedString = Pattern.compile("[{}\\[\\]]").matcher(replacedStr).replaceAll("");
        String finalResult = "{"+cleanedString+"}";
        System.out.println("清除后结果："+finalResult);
        // 创建一个JSONObject来存储提取的信息
        JSONObject extractedInfo = new JSONObject();
        //
        try {
            // 解析JSON字符串为JSONObject
            JSONObject json = JSON.parseObject(finalResult);
            // 遍历字段列表，提取或设置null值
            for (String fieldName : fields) {
                Object value = json.get(fieldName);
                extractedInfo.put(fieldName, value != null ? value.toString() : "无信息");
            }
            System.out.println("JSON格式数据处理完毕：\n" + extractedInfo);
            return extractedInfo.toJSONString();
        } catch (JSONException e) {

            // JSON解析异常，尝试按行解析
            String[] lines = finalResult.split("\n");
            for (String line : lines) {
                line = line.trim();
                if (!line.isEmpty()) {
                    String[] keyValue = line.split("：");
                    if (keyValue.length == 2) {
                        extractedInfo.put(keyValue[0].trim(), keyValue[1].trim());
                    }
                }
            }
            if (extractedInfo.isEmpty()) {
                // 如果还是没提取到数据，直接输出finalResult
                System.out.println("无法解析的数据：" + finalResult);
                return finalResult;
            } else {
                System.out.println("非JSON格式数据处理完毕：" + extractedInfo.toJSONString());
                return extractedInfo.toJSONString();
            }

        }catch (Exception e) {
            System.out.println(finalResult);
            return finalResult;
        }
    }
}





